﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using MiniX.Manage.Data;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;
using Microsoft.EntityFrameworkCore;
using MiniX.Utility.Helper;
using System.Text;
using Markdig;

// For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace MiniX.Manage.Controllers
{
    /// <summary>
    /// 版权所有: Copyright © 2023 Cloudin. 保留所有权利。
    /// 内容摘要: 控制台主页面
    /// 创建日期：2023年4月9日
    /// 更新日期：2023年4月21日
    /// 版    本：V1.0.86 
    /// 作    者：Cloudin
    /// </summary>
    public class MainController : BaseController<MainController>
    {
        public MainController(MiniXManageContext context) : base(context)
        {

        }

        // GET: /<controller>/
        public IActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 控制台页面
        /// </summary>
        /// <returns></returns>
        public IActionResult Console()
        {
            return View();
        }

        /// <summary>
        /// 日志更新页面
        /// </summary>
        /// <returns></returns>
        public IActionResult Update()
        {
            return View();
        }

        /// <summary>
        /// 读取更新日志
        /// </summary>
        /// <returns></returns>
        [HttpGet("/main/updatelogs")]
        public async Task<IActionResult> UpdateLogs()
        {
            try
            {
                var md_file = Directory.GetCurrentDirectory() + "/update.md";
                var content = "";
                using (var file = new FileStream(md_file, FileMode.Open))
                {
                    byte[] buffer = new byte[file.Length];
                    await file.ReadAsync(buffer);

                    content = Encoding.Default.GetString(buffer);
                }

                var pipeline = new MarkdownPipelineBuilder().UseAdvancedExtensions().Build();
                content = Markdown.ToHtml(content, pipeline);

                var data = new
                {
                    logs = content,
                    version_code = MiniX.Manage.Filters.AppSettingsFilter.GetSetting("Setting:VersionCode")
                };

                return Json(new { code = 0, msg = "success", data = data });
            }
            catch (Exception ex)
            {
                log.Fatal(ex, " -> Details");
                return Json(new { code = 0, errcode = (int)ENUMHelper.ExceptionType.Details, errmsg = ex.Message });
            }
        }
    }
}
